
import os
import re
import subprocess
import sys
import datetime
import re
import gradio as gr



import random
import string

import ssl


def get_tex_files(main_file):
    """获取主文件的目录和所有被引用的tex文件"""
    directory = os.path.dirname(main_file)
    included_files = []

    with open(main_file, 'r', encoding='utf-8') as f:
        content = f.read()

        # 匹配 \input 和 \include 命令
        inputs = re.findall(r'\\(?:input|include)\s*{([^}]+)}', content)

        for file in inputs:
            full_path = os.path.join(directory, f"{file}.tex")
            if os.path.exists(full_path):
                included_files.append((file, full_path))

    return included_files

def merge_tex_files(main_file, output_tex_file):
    """合并所有tex文件"""
    included_files = get_tex_files(main_file)

    with open(output_tex_file, 'w', encoding='utf-8') as outfile:
        # 写入主文件内容
        with open(main_file, 'r', encoding='utf-8') as f:
            content = f.read()

            # 替换 \input 和 \include 命令
            for name, path in included_files:
                with open(path, 'r', encoding='utf-8') as included_file:
                    included_content = included_file.read()
                    content = content.replace(f'\\input{{{name}}}', included_content)
                    content = content.replace(f'\\include{{{name}}}', included_content)

            # 写入合并后的内容
            outfile.write(content)
            outfile.write('\n% Merged content below\n')

def convert_to_markdown(tex_file, markdown_file):
    """使用pandoc将LaTeX文件转换为Markdown文件"""
    command = ['pandoc', tex_file, '-o', markdown_file]

    try:
        subprocess.run(command, check=True)
        print(f'Markdown file created: {markdown_file}')
    except subprocess.CalledProcessError as e:
        print(f'Error occurred while converting to Markdown: {e}')

def test():
    if len(sys.argv) != 3:
        print("Usage: python main.py <input_tex_file> <output_tex_file>")
        sys.exit(1)

    main_tex_file = sys.argv[1]  # 输入的主TeX文件路径
    output_tex_file = sys.argv[2]  # 输出的合并TeX文件名

    merge_tex_files(main_tex_file, output_tex_file)
    print(f'Merged LaTeX file created: {output_tex_file}')

    # 转换为Markdown
    markdown_file = output_tex_file.replace('.tex', '.md')
    convert_to_markdown(output_tex_file, markdown_file)




#



home = os.path.expanduser("~")

def get_default_output_folder():
    return os.path.join(home, "Downloads")


def generate_filename(filetype= 'md'):
    """生成基于时间和随机字符的文件名"""
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
    return f"src-merge-{timestamp}_{random_string}.{filetype}"




examples=[
        ["/Users/Shared/work_cache/data_examples/tex_folder-to-big-texs/arXiv-2407.08561v1/paper_tex.tex", ""],
        ["/Users/Shared/work_cache/data_examples/tex_folder-to-big-texs/arXiv-2407.08561v1/paper_tex.tex", "/Users/Shared/work_cache/output_cache/merged_src.tex" ],
    ]


# 禁用SSL验证
ssl._create_default_https_context = ssl._create_unverified_context

def process_folder(input_main_tex_file, output_tex_file ):
    #

    input_main_tex_file = input_main_tex_file.strip()

    if not output_tex_file.strip():
        output_tex_file = get_default_output_folder() + '/'+generate_filename(filetype='tex')

    message = ''

    try:
        print(input_main_tex_file, output_tex_file)
        merge_tex_files(input_main_tex_file, output_tex_file)
        print(f'Merged LaTeX file created: {output_tex_file}')

        message += f"成功创建合并tex文档：{output_tex_file}"

    except Exception as e:
        message += f"处理【创建合并tex文档】过程中出错：{str(e)}"
        return message
    #
    # 转换为Markdown
    # # try捕捉错误
    try:
        output_markdown_file = output_tex_file.replace('.tex', '.md')
        convert_to_markdown(output_tex_file, output_markdown_file)

        message += f"\n成功创建合并markdown文档：{output_markdown_file}"
    except Exception as e:
        print('[find error]' ,e )
        message += f"\n创建合并markdown文档失败：{e}"
    #
    return message

# 创建Gradio接口
iface = gr.Interface(
    fn=process_folder,
    inputs=[
        gr.Textbox(label="输入tex文件路径"),
        gr.Textbox(label="输出tex文件路径（包括文件名）")
    ],
    outputs=gr.Textbox(label="处理结果"),
    title="latex项目仓库合并工具",
    description="选择一个main的tex文件，指定输出文件路径。",
    examples= examples
)

# 运行Gradio应用
if __name__ == "__main__":
    # 从环境变量获取端口，如果没有设置，默认使用7860
    port = int(os.environ.get("PORT", 34923 ))

    # 启动Gradio应用，设置端口并禁用SSL
    iface.launch(server_name="0.0.0.0", server_port=port, ssl_verify=False)





#
#
#
#  python3 main.py  paper_tex.tex
#
